package cosc455.project1;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

/**
 * Compiler Accepts the name of a input text file to be parsed and converted
 * into HTML
 * 
 * @author BinhDang
 *
 */
public class Compiler {
	// String of Current Token
	public static String currentToken;

	public static LexicalAnalyzer Lexer;

	// Holds the file name
	public static String filePrefix;

	/**
	 * This method grabs the file name by removing the extension of a file. Used
	 * for naming HTML file.
	 * 
	 * @param s
	 *            Current string
	 */
	public static void getFileName(String s) {
		filePrefix = (s.substring(0, s.indexOf('.')));
	}

	public static void main(String[] args) throws IOException {
		Lexer = new LexicalAnalyzer();
		int a;
		String s;
		CharSequence cs = ".lol";

		StringBuilder str = new StringBuilder();
		SyntaxAnalyzer Parser = new SyntaxAnalyzer();

		File inFile = null;
		inFile = new File(args[0]);

		s = inFile.getName();
		getFileName(s);
		FileReader fr = new FileReader(inFile);
		BufferedReader br = new BufferedReader(fr);

		// Tests the extension of file
		// Only files that end in "lol" are allowed
		if (s.endsWith((String) cs)) {

			String sourceLine = null;

			while ((a = br.read()) != -1) {
				str.append((char) a);
			}

			sourceLine = str.toString();
			sourceLine.replaceAll("[\\s\\u00A0]+$", "");

			Lexer.start(sourceLine);

			Parser.lolcode();

			// Won't create HTML file if error was found
			if (!SyntaxAnalyzer.errorFlag) {
				SemanticAnalyzer.build();
			}

		} else {
			System.out.println("Error: " + s
					+ " is not a valid file. Must use file with lol extension");
		}

		fr.close();

	}

}